#!/usr/bin/python
#coding:utf-8
# Author:   --<>
# Purpose: 
# Created: 2010-01-08
from PyQt4 import QtCore
from pyDes import *
from binascii import unhexlify as unhex
import base64,yaml,traceback
from wordpresslib import WordPressClient,WordPressPost

LANG_ZH_CN = {"name":u"简体中文","value":"zh-CN"}
LANG_ZH_TW = {"name":u"繁体中文","value":"zh-TW"}
LANG_EN = {"name":u"英语","value":"en"}

locs  = [LANG_EN,LANG_ZH_CN,LANG_ZH_TW]


blogs = yaml.load(file('blogs.yml', 'r').read())

categories = {}

def decrypt(st):
    k1 = des(unhex("133457799BBCDFF1"))
    d = base64.decodestring(st)
    rs = None
    try:
        rs = k1.decrypt(d).strip()
    except:
        traceback.print_exc() 
        return None
    return rs.split(":")

def postBlog(blog):
    if not blog:
        return   
    blogname = blog['blogname']
    title = blog['title']
    desc = blog['desc']
    categories = blog['categories']
    tag = blog['tag']
    apiurl =  blogs[blogname]['apiurl']
    auth = decrypt(blogs[blogname]['authkey'])
    wp = WordPressClient(apiurl, auth[0], auth[1])
    post = WordPressPost()
    post.title = title
    post.description = desc
    post.categories = (wp.getCategoryIdFromName(categories),)
    try:
        wp.newPost(post, True)    
        return True
    except:
        traceback.print_exc() 
        return False
    

def getCategory(blogname):
   apiurl = blogs[blogname]['apiurl']
   auth = decrypt(blogs[blogname]['authkey'])
   wp = WordPressClient(apiurl, auth[0], auth[1])
   try:
       return wp.getCategoryList()
   except:
       traceback.print_exc() 
       return []

class PostThread(QtCore.QThread):
    bloglist = []
    def addBlog(self,blog):
       if len(self.bloglist) == 0:
           self.bloglist.append(blog)    
       else:
           for b in self.bloglist:
               if blog['title'] != b['title']:
                   bloglist.append(blog)
               else:
                   print u"blog %s 重复"%blog['title']

    def run(self):
        while True:
            if self.bloglist:
                b = self.bloglist.pop()
                while b:
                    try:
                        print postBlog(b)
                        if self.bloglist:
                            b = self.bloglist.pop()
                    except:
                        traceback.print_exc() 
            QtCore.QThread.sleep(3)

class CategoryThread(QtCore.QThread):
    def run(self):
        global categories
        for blogname in blogs:
            try:
                cs = getCategory(blogname)
                categories[blogname]= [it.name for it in cs]
            except:
                pass

if __name__ == "__main__":
    CategoryThread("jamiesuncn")
